import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Button, Text, Avatar } from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';

// 菜单项接口
interface MenuItem {
  id: string;
  label: string;
  icon: string;
  path: string;
  roles: ('admin' | 'user' | 'guest')[];
  children?: MenuItem[];
}

const menuItems: MenuItem[] = [
  {
    id: 'dashboard',
    label: '首页',
    icon: '📊',
    path: '/app',
    roles: ['admin', 'user', 'guest'],
  },
   { 
    id: 'student-management',
    label: '学生管理',
    icon: '👨‍🎓',
    path: '/app/students',
    roles: ['admin', 'user'],
    children: [
      { 
        id: 'student-list',
        label: '学生列表',
        icon: '📋',
        path: '/app/students',
        roles: ['admin', 'user'],
      },
    ],
  },
  { 
    id: 'grade-management',
    label: '成绩管理',
    icon: '👨',
    path: '/app/grades',
    roles: ['admin', 'user'],
    children: [
      { 
        id: 'grade-list',
        label: '成绩列表',
        icon: '📋',
        path: '/app/grades',
        roles: ['admin', 'user'],
      },
    ],
  },
  
  {
    id: 'teacher-management',
    label: '教师管理',
    icon: '👨‍🏫',
    path: '/app/teachers',
    roles: ['admin', 'user'],
    children: [
      {
        id: 'teacher-list',
        label: '教师列表',
        icon: '📋',
        path: '/app/teachers',
        roles: ['admin', 'user'],
      },
    ],
  },
  {    id: 'dormitory-management',    label: '宿舍管理',    icon: '🏠',    path: '/app/dormitories',    roles: ['admin', 'user'],    children: [      {        id: 'dormitory-list',        label: '宿舍列表',        icon: '📋',        path: '/app/dormitories',        roles: ['admin', 'user'],      },    ],  },  {    id: 'dormitory-building-management',    label: '宿舍楼管理',    icon: '🏢',    path: '/app/dormitory-buildings',    roles: ['admin', 'user'],    children: [      {        id: 'dormitory-building-list',        label: '宿舍楼列表',        icon: '📋',        path: '/app/dormitory-buildings',        roles: ['admin', 'user'],      },    ],  },
  {
    id: 'counselor-management',
    label: '辅导员管理',
    icon: '👨‍⚖️',
    path: '/app/counselors',
    roles: ['admin', 'user'],
    children: [
      {
        id: 'counselor-list',
        label: '辅导员列表',
        icon: '📋',
        path: '/app/counselors',
        roles: ['admin', 'user'],
      },
    ],
  },
  { 
    id: 'class-management',
    label: '班级管理',
    icon: '🏫',
    path: '/app/classes',
    roles: ['admin', 'user'],
    children: [
      { 
        id: 'class-list',
        label: '班级列表',
        icon: '📋',
        path: '/app/classes',
        roles: ['admin', 'user'],
      },
    ],
  },
  
  { 
    id: 'college-management',
    label: '学院管理',
    icon: '🏢',
    path: '/app/colleges',
    roles: ['admin', 'user'],
    children: [
      { 
        id: 'college-list',
        label: '学院列表',
        icon: '📋',
        path: '/app/colleges',
        roles: ['admin', 'user'],
      },
    ],
  },
  
 
  
  {
    id: 'comprehensive-score-management',
    label: '综合积分管理',
    icon: '⭐',
    path: '/app/comprehensive-scores',
    roles: ['admin', 'user'],
    children: [
      {
        id: 'comprehensive-score-list',
        label: '积分列表',
        icon: '📋',
        path: '/app/comprehensive-scores',
        roles: ['admin', 'user'],
      },
    ],
  },
   { 
    id: 'market-department-management',
    label: '市场部管理',
    icon: '💼',
    path: '/app/market-departments',
    roles: ['admin', 'user'],
    children: [
      { 
        id: 'market-department-list',
        label: '市场部列表',
        icon: '📋',
        path: '/app/market-departments',
        roles: ['admin', 'user'],
      },
    ],
  },
 
];

interface SidebarProps {
  isCollapsed: boolean;
  onToggle: () => void;
}


export default function Sidebar({ isCollapsed, onToggle }: SidebarProps) {
  const navigate = useNavigate();
  const location = useLocation();
  const { session, logout } = useSession();
  const [expandedItems, setExpandedItems] = useState<string[]>([]);
  const [transitioning, setTransitioning] = useState(false);

  // 处理折叠状态变化时的过渡效果
  useEffect(() => {
    setTransitioning(true);
    const timer = setTimeout(() => setTransitioning(false), 300);
    return () => clearTimeout(timer);
  }, [isCollapsed]);

  // 检查用户是否有权限访问菜单项
  const hasPermission = (item: MenuItem): boolean => {
    if (!session) return false;
    return item.roles.includes(session.userRole);
  };

  // 检查是否有子菜单权限
  const hasChildrenPermission = (item: MenuItem): boolean => {
    if (!item.children) return false;
    return item.children.some((child) => hasPermission(child));
  };

  // 切换子菜单展开状态
  const toggleExpanded = (itemId: string) => {
    setExpandedItems((prev) =>
      prev.includes(itemId)
        ? prev.filter((id) => id !== itemId)
        : [...prev, itemId]
    );
  };

  // 处理菜单点击
  const handleMenuClick = (item: MenuItem) => {
    if (item.children && hasChildrenPermission(item)) {
      toggleExpanded(item.id);
    } else {
      navigate(item.path);
    }
  };

  // 检查菜单项是否激活
  const isActive = (item: MenuItem): boolean => {
    if (item.children) {
      return item.children.some((child) => location.pathname === child.path);
    }
    return location.pathname === item.path;
  };

  // 处理登出
  const handleLogout = async () => {
    await logout();
    navigate('/login');
  };

  // 根据用户ID生成颜色
  const getAvatarColor = (id: number | string) => {
    const colors = [
      'bg-blue-500',
      'bg-indigo-500',
      'bg-purple-500',
      'bg-pink-500',
      'bg-red-500',
      'bg-orange-500',
      'bg-yellow-500',
      'bg-green-500',
      'bg-teal-500',
      'bg-cyan-500',
    ];
    const idStr = String(id);
    const hash = idStr
      .split('')
      .reduce((acc, char) => acc + char.charCodeAt(0), 0);
    return colors[hash % colors.length];
  };

  if (!session) {
    return null;
  }

  const avatarColor = getAvatarColor(session.userId);

  return (
    <div
      className={`bg-white dark:bg-gray-800 shadow-md transition-all duration-300 ease-in-out ${
        isCollapsed ? 'w-16' : 'w-72'
      } fixed h-full z-30 border-r border-gray-200 dark:border-gray-700 overflow-hidden`}
    >
      {/* 侧边栏头部 */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between bg-gradient-to-r from-blue-500 to-indigo-600 text-white">
        <div
          className={`flex items-center space-x-2 ${
            transitioning && !isCollapsed
              ? 'opacity-100'
              : transitioning && isCollapsed
              ? 'opacity-0'
              : ''
          } transition-opacity duration-200`}
        >
          <span className="text-xl">🏫</span>
          {!isCollapsed && (
            <Text className="text-lg font-bold whitespace-nowrap">
              师生管理系统
            </Text>
          )}
        </div>
        <Button
          variant="ghost"
          size="sm"
          onClick={onToggle}
          className={`p-1 rounded-full hover:bg-white/20 transition-colors ${
            isCollapsed ? 'mx-auto' : ''
          }`}
          style={{ color: 'white' }}
        >
          {isCollapsed ? '→' : '←'}
        </Button>
      </div>

      {/* 用户信息 */}
      <div
        className={`p-4 border-b border-gray-200 dark:border-gray-700 transition-all duration-300 ${
          isCollapsed ? 'justify-center' : ''
        } flex items-center`}
      >
        <div
          className={`${avatarColor} rounded-full flex items-center justify-center w-10 h-10 shadow-md`}
        >
          <Text className="text-white text-sm font-bold">
            {session.userName.charAt(0).toUpperCase()}
          </Text>
        </div>
        {!isCollapsed && (
          <div
            className={`flex-1 ml-3 min-w-0 ${
              transitioning ? 'opacity-100' : 'opacity-100'
            }`}
          >
            <Text className="text-sm font-medium text-gray-900 dark:text-white truncate">
              {session.userName}
            </Text>
            <Text className="text-xs text-gray-500 dark:text-gray-400">
              {session.userRole === 'admin'
                ? '管理员'
                : session.userRole === 'user'
                ? '用户'
                : '访客'}
            </Text>
          </div>
        )}
      </div>

      {/* 菜单项 */}
      <nav className="flex-1 p-2 overflow-y-auto">
        <div className="space-y-1">
          {menuItems.map((item) => {
            if (!hasPermission(item) && !hasChildrenPermission(item)) {
              return null;
            }

            const hasChildren = item.children && hasChildrenPermission(item);
            const isExpanded = expandedItems.includes(item.id);
            const active = isActive(item);

            return (
              <div key={item.id} className="group">
                {/* 主菜单项 */}
                <Button
                  variant="ghost"
                  onClick={() => handleMenuClick(item)}
                  className={`w-full justify-start transition-all duration-200 ease-in-out ${
                    isCollapsed ? 'px-2 py-3' : 'px-3 py-2.5'
                  } rounded-lg hover:shadow-sm ${
                    active
                      ? 'bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-800/40'
                      : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700/50'
                  }`}
                >
                  <span
                    className={`${
                      isCollapsed ? 'text-xl' : 'text-lg'
                    } mr-3 flex-shrink-0`}
                  >
                    {item.icon}
                  </span>
                  {!isCollapsed && (
                    <>
                      <span className="flex-1 text-left font-medium">
                        {item.label}
                      </span>
                      {hasChildren && (
                        <span
                          className={`transform transition-transform duration-300 ${
                            isExpanded ? 'rotate-90' : ''
                          }`}
                        >
                          ▶
                        </span>
                      )}
                    </>
                  )}
                </Button>

                {/* 子菜单项 */}
                {hasChildren && isExpanded && !isCollapsed && (
                  <div className="ml-9 mt-1 space-y-1 animate-fadeIn">
                    {item.children!.map((child) => {
                      if (!hasPermission(child)) return null;

                      const childActive = location.pathname === child.path;

                      return (
                        <Button
                          key={child.id}
                          variant={childActive ? 'primary' : 'ghost'}
                          onClick={() => navigate(child.path)}
                          className={`w-full justify-start px-3 py-2 transition-all duration-200 ${
                            childActive
                              ? 'bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-800/40'
                              : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700/50'
                          }`}
                        >
                          <span className="text-sm mr-2">{child.icon}</span>
                          <span className="text-sm font-medium">
                            {child.label}
                          </span>
                        </Button>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </nav>

      {/* 底部操作 */}
      <div className="p-4 border-t border-gray-200 dark:border-gray-700">
        <Button
          variant="ghost"
          onClick={handleLogout}
          className={`w-full justify-start transition-all duration-200 ${
            isCollapsed ? 'px-2 py-2.5' : 'px-3 py-2'
          } rounded-lg text-red-600 dark:text-red-400 hover:text-red-800 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900/20`}
        >
          <span className="text-lg mr-3">🚪</span>
          {!isCollapsed && <span className="font-medium">安全登出</span>}
        </Button>
      </div>
    </div>
  );
}